package com.base.cn.platform.os.controller.user.user;

import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.md5.MD5;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.user.LoginForm;
import com.base.cn.platform.os.common.utils.user.ProfileType;
import com.base.cn.platform.os.common.utils.user.UserExpandFrom;
import com.base.cn.platform.os.entity.user.user.CusUser;
import com.base.cn.platform.os.entity.user.user.CuserProfile;
import com.base.cn.platform.os.service.manage.config.SysConfigBiz;
import com.base.cn.platform.os.service.user.user.CusUserBiz;
import com.base.cn.platform.os.service.user.user.CuserProfileBiz;
import com.base.cn.platform.os.service.user.user.UserLoginBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;


/**
 * 第三方登录数据接口
 *
 * @author s.li
 * @create 2018-08-30-21:00
 */
@RestController
@RequestMapping("/manage/user")
public class CuserProfileController extends BaseController {
    @Autowired
    private CuserProfileBiz cuserProfileBiz;
    @Autowired
    private CusUserBiz cusUserBiz;
    @Autowired
    private UserLoginBiz userLoginBiz;
    @Autowired
    SysConfigBiz sysConfigBiz;

    /**
     * 保存第三方登录数据
     * @param cuserProfile 数据对象
     * @param registerFrom 注册来源
     * @return CuserProfile 返回保存的数据对象
     */
    @RequestMapping("/saveUserProfile")
    public Map<String,Object> saveUserProfile(HttpServletRequest request,@RequestBody CuserProfile cuserProfile,
                                              @RequestParam("registerFrom") String registerFrom)throws IOException {
        String remind = thirdPartySwitch(cuserProfile.getProfileType());
        boolean version = false;
        String versionNum = cuserProfile.getVersion();
        version = this.targetBindMobile(registerFrom, versionNum);
        if(StringUtils.isNotEmpty(remind)){
            return ResultUtil.ERROR(remind);
        }
        System.out.println(version);
        cuserProfile = cuserProfileBiz.saveUserProfile(cuserProfile,registerFrom,version);
        CusUser user = new CusUser();
        if(DataUtil.idIsNotNull(cuserProfile.getUserId())){
            user = cusUserBiz.findById(cuserProfile.getUserId());
        }
        if(user.getIsavalible().intValue()!=1){
            return ResultUtil.ERROR("帐号已被冻结，暂不允许登录");
        }
        String sessionId = MD5.getMD5(System.currentTimeMillis()+ StringUtils.getRandomString(32)+cuserProfile.getId());
        String loginForm = null;
        if(registerFrom.equals(UserExpandFrom.registerFrom.getKey())
                || registerFrom.equals(UserExpandFrom.pcThirdQQ.getKey())
                || registerFrom.equals(UserExpandFrom.pcThirdWeiXin.getKey())){
            loginForm = LoginForm.LOGIN_FROM_PC;
        }else if(registerFrom.equals(UserExpandFrom.mobileFrom.getKey())
                || registerFrom.equals(UserExpandFrom.mobileThirdQQ.getKey())
                || registerFrom.equals(UserExpandFrom.mobileThirdWeiXin.getKey())){
            loginForm = LoginForm.LOGIN_FROM_MOBILE;
        } else if (registerFrom.equals(UserExpandFrom.iosFrom.getKey())
                || registerFrom.equals(UserExpandFrom.androidFrom.getKey())
                || registerFrom.equals(UserExpandFrom.ios.getKey())
                || registerFrom.equals(UserExpandFrom.iosThirdWeiXin.getKey())
                || registerFrom.equals(UserExpandFrom.androidThirdWeiXin.getKey())
                || registerFrom.equals(UserExpandFrom.iosThirdQQ.getKey())
                || registerFrom.equals(UserExpandFrom.androidThirdQQ.getKey())
                || registerFrom.equals(UserExpandFrom.iosLogin.getKey())) {
            loginForm = LoginForm.LOGIN_FORM_APP;
        } else if (registerFrom.equals(UserExpandFrom.appletThirdWeiXin.getKey())) {
            loginForm = LoginForm.LOGIN_FORM_APPLET;
        }
        //设置用户登录数据
        userLoginBiz.setUserLoginInfo(user,false,null);
        user.setPassword(null);
        user.setCustomerkey(null);
        user.setOther(true);
        user.setCpId(cuserProfile.getId());
        if (version) {
            user.setMobileIsavalible(1);
        }
        //缓存用户
        Map<String,Object> resultMap = userLoginBiz.setUserCache(request,user,sessionId,"false",loginForm);
        String status = (String)resultMap.get("status");
        if(StringUtils.isEmpty(status)){
            ResultUtil.setEntity(resultMap,user);
        }
        return resultMap;
    }

    /**
     * 获取第三方登录数据
     * @param userId 用户id
     * @return CuserProfile 返回保存的数据对象
     */
    @RequestMapping("/findUserProfile")
    public List<CuserProfile> findUserProfile(
            @RequestParam("userId") BigDecimal userId) {
        return cuserProfileBiz.find("userId=" + userId, null, null);

    }

    /**
     * 获取第三方登录数据已userId做key的Map
     * @param userIds 用户id
     * @return CuserProfile 返回保存的数据对象
     */
    @RequestMapping("/findUserProfileMapList")
    public Map<String, List<CuserProfile>>  findUserProfileMapList(
            @RequestParam("userIds") String userIds) {

        return  cuserProfileBiz.findUserProfileMapList(userIds);
    }


    public     String thirdPartySwitch(String appType){

        //开关配置
        TreeMap<String,String> onOffConfig = sysConfigBiz.getSysConfigContext(ConfigName.ONOFF);
        //ON代表开启;OFF代表关闭
        if(appType.equals(ProfileType.QQ.toString())){
            if(!onOffConfig.get("qqLoginSwitch").equals("ON")) {
                return  "已禁用QQ登录";
            }
        }else if(appType.equals(ProfileType.WEIXIN.toString())){
            if(!onOffConfig.get("weiXinLoginSwitch").equals("ON")) {
                return  "已禁用微信登录";
            }
        }
        return  "";
    }

    /**
     * 如果第三方账号登录是苹果账号，则跳过手机号绑定操作
     * @param registerFrom
     * @param iosVersion
     * @return
     */
    private boolean targetBindMobile(String registerFrom,String iosVersion) {
        boolean greater = false;
        if (registerFrom.equals(UserExpandFrom.iosLogin.getKey())) {
            TreeMap<String, String> appSet = sysConfigBiz.getSysConfigContext(ConfigName.APP);
            String sysIosVersion = appSet.get("iosVersion"); // 系统设置的ios 版本
            System.out.println(sysIosVersion + "/" + iosVersion);
            if (StringUtils.isNotEmpty(iosVersion) && StringUtils.isNotEmpty(sysIosVersion)) {
                String[] iosVersionArr = iosVersion.split("\\.");
                String[] sysIosVersionArr = sysIosVersion.split("\\.");
                for (int i = 0; i < iosVersionArr.length; i++) {
                    Integer singleNum = Integer.parseInt(iosVersionArr[i]);
                    Integer sysSingleNum = Integer.parseInt(sysIosVersionArr[i]);
                    if (singleNum > sysSingleNum) {
                        greater = true;
                        break;
                    }
                    if (singleNum < sysSingleNum) {
                        greater=false;
                        break;
                    }
                }
            }
        }
        return greater;
    }
}
